<template>
  <div class="car-match-box">
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="searchFilter" />

    <table-index :table="form.customCarList">
      <template #table-summary>
        <div class="car-match-box-count">
          <div class="item">
            OTA车辆总数：<span class="num">{{ form.customCarList.dataList.length }}</span>
          </div>
          <div class="item">
            未匹配车辆数：<span class="num">{{ getUnMatchCarNum }}</span>
          </div>
        </div>
      </template>
      <template #channelSite="{ record }">
        <div>{{ record.channelSite }}</div>
        <div>{{ record.channelModel }}</div>
      </template>
      <template #channelCarLicenseNo="{ record, rowIndex }">
        <span v-if="record.id">
          {{ record.channelCarLicenseNo }}
        </span>
        <page-form-item
          v-else
          size="1/2"
          style="margin-bottom: 0"
          :field="`customCarList.dataList.${rowIndex}.channelCarLicenseNo`"
          :rules="{ required: true, message: '请输入' }"
          required
        >
          <i-input v-model="record.channelCarLicenseNo" :max-length="10" />
        </page-form-item>
      </template>
      <template #relationCarLicenseNo="{ record, rowIndex }">
        <template v-if="record.status === 'create'">
          {{ record.relationCarLicenseNo }}
        </template>
        <page-form-item v-else style="margin-bottom: 0" size="1/2">
          <remote-select
            style="width: 100%"
            v-model="record.relationCarId"
            :index="rowIndex"
            type="car_licenseno_list"
            @change="onCarChange"
            :popupContainer="'.page-container'"
            :updateAtScroll="true"
            :scrollToClose="true"
          />
        </page-form-item>
      </template>
    </table-index>
  </div>
</template>

<script setup lang="ts">
  import { ref, inject, computed, reactive, onMounted } from 'vue'
  import { getChannelPlateList, syncAccount, deleteChannelPlate, syncAccountInfoStatus, saveChannelPlate } from '@/api/business/ota'
  import getFuncOnLoopCondition from '@/utils/getFuncOnLoopCondition'
  import { useTable } from '@/hooks/table'
  import { Message } from '@arco-design/web-vue'
  import { useRoute } from 'vue-router'

  const route = useRoute()
  const { params, query } = route
  console.log(route, 'car-match')

  const props = defineProps({
    accountId: String,
  })

  const form = ref(inject<any>('form'))
  const formRef = inject<any>('formRef')
  form.value.customCarList = useTable({
    tableLoading: false,
    pagination: false,
    columns: [
      {
        title: 'OTA渠道车辆信息',
        dataIndex: 'channelSite',
        key: 'channelSite',
        slotName: 'channelSite',
      },
      {
        title: '渠道车牌号',
        dataIndex: 'channelCarLicenseNo',
        key: 'channelCarLicenseNo',
        slotName: 'channelCarLicenseNo',
      },
      {
        title: '商户车牌号',
        dataIndex: 'relationCarLicenseNo',
        key: 'relationCarLicenseNo',
        slotName: 'relationCarLicenseNo',
      },
    ],
    operates: [
      {
        label: '修改',
        show: (record: any) => record.id && record.status === 'create',
        method: (record: any, column: any, rowIndex: number) => {
          console.log(record, column, rowIndex)
          record.status = 'edit'
        },
      },
      {
        label: '保存',
        show: (record: any) => record.status === 'edit',
        method: (record: any, column: any, rowIndex: number) => {
          console.log(record, column, rowIndex)
          onSaveCarMatch(record)
        },
      },
      {
        label: '删除',
        type: 'danger',
        method: (record: any, column: any, rowIndex: number) => {
          formRef.value.clearValidate()
          if (record.id) {
            deleteChannelPlate({ id: record.id }).then((res: any) => {
              console.log(res, '删除车牌 deleteChannelCar')
              form.value.customCarList.dataList.splice(rowIndex, 1)
              loadData()
              queryParam.channelSite = ''
              queryParam.channelCarLicenseNo = ''
              queryParam.relationCarId = ''
              queryParam.sourceType = ''
            })
          } else {
            form.value.customCarList.dataList.splice(rowIndex, 1)
          }
        },
      },
    ],
    buttons: [
      {
        // permission: 'svms:asstes:car:car-model:add',
        label: '同步车辆',
        show: () => params.id && query.sourceStatus != '3',
        method: () => {
          Message.info('同步中，请稍后')
          onSynCarMatch()
        },
      },
      {
        type: 'primary',
        // permission: 'svms:asstes:car:car-model:add',
        icon: 'plus',
        label: '新增',
        method: () => {
          formRef.value.clearValidate()
          onAddCarMatch()
        },
      },
    ],
    dataList: [],
  })

  const queryParam = reactive<any>({})
  const searchList = computed(() => {
    return [
      { label: 'OTA渠道门店', prop: 'channelSite', type: 'a-input', span: 1 },
      { label: '渠道车牌号', prop: 'channelCarLicenseNo', type: 'a-input', span: 1 },
      {
        label: '商户车牌号',
        prop: 'relationCarId',
        type: 'remote-select',
        attrs: {
          type: 'car_licenseno_list',
        },
      },
      {
        label: '商户车牌配置',
        prop: 'sourceType',
        type: 'a-select',
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '0',
          },
        ],
      },
    ]
  })

  const onCarChange = (value: any, option: any, index: number) => {
    console.log(value, option, index, 'onCarChange')
    form.value.customCarList.dataList[index].relationCarLicenseNo = option.licenseNo
  }

  const onSaveCarMatch = (record: any) => {
    console.log('保存车牌', record)
    saveChannelPlate(record).then((res: any) => {
      console.log(res, '保存车牌 saveChannelPlate')
      record.status = 'create'
      // loadData()
      // queryParam.channelSite = ''
      // queryParam.channelCarLicenseNo = ''
      // queryParam.relationCarId = ''
      // queryParam.sourceType = ''
    })
  }

  const onAddCarMatch = () => {
    searchFilter()
    form.value.customCarList.dataList.unshift({
      channelSite: '',
      channelCarLicenseNo: '',
      relationCarId: '',
      accountId: params.id || props.accountId,
    })
  }

  // 未匹配车辆数
  const getUnMatchCarNum = computed(() => {
    return form.value.customCarList.dataList.filter((item: any) => !item.relationCarId).length
  })

  const searchFilter = () => {
    form.value.customCarList.dataList = shadowCustomCarList.list

    const result: any = []
    for (let i = 0; i < form.value.customCarList.dataList.length; i++) {
      if (queryParam.channelSite) {
        if (!form.value.customCarList.dataList[i].channelSite?.includes(queryParam.channelSite)) {
          continue
        }
      }

      if (queryParam.channelCarLicenseNo) {
        if (form.value.customCarList.dataList[i].channelCarLicenseNo !== queryParam.channelCarLicenseNo) {
          continue
        }
      }

      if (queryParam.relationCarId) {
        console.log(queryParam.relationCarId, 'relationCarId')

        if (form.value.customCarList.dataList[i].relationCarId !== +queryParam.relationCarId) {
          continue
        }
      }

      if (queryParam.sourceType) {
        if (queryParam.sourceType === '0') {
          if (form.value.customCarList.dataList[i].relationCarId) {
            continue
          }
        }
        if (queryParam.sourceType === '1') {
          if (!form.value.customCarList.dataList[i].relationCarId) {
            continue
          }
        }
      }

      result.push(form.value.customCarList.dataList[i])
    }

    console.log(result, queryParam, Object.keys(queryParam).length, 'result')

    form.value.customCarList.dataList = result

    const isEmpty = Object.keys(queryParam).every((key: any) => {
      return !queryParam[key]
    })
    if (isEmpty) {
      form.value.customCarList.dataList = shadowCustomCarList.list
    }
  }

  // 检查同步账号信息状态
  const checkSyncAccountCondition = (response: any) => {
    return response.result === 0
  }

  // 同步车辆
  const onSynCarMatch = () => {
    syncAccount({ id: params.id || props.accountId }).then((res: any) => {
      // Message.success('同步成功')
      console.log(res, '同步车辆 syncAccountStore')
      const executor = async () => {
        const response = await syncAccountInfoStatus({ id: params.id || props.accountId })
        return response
      }
      const condition = checkSyncAccountCondition
      const delay = 1000
      getFuncOnLoopCondition(executor, condition, delay)
        .then(() => {
          loadData()
          queryParam.channelSite = ''
          queryParam.channelCarLicenseNo = ''
          queryParam.relationCarId = ''
          queryParam.sourceType = ''
        })
        .catch((error: any) => {
          // Message.error(error.message)
          console.log(error, '同步车辆 error')
        })
    })
  }

  const copyCustomCarList = ref()
  const shadowCustomCarList = reactive<any>({
    list: [],
  })
  const loadData = () => {
    getChannelPlateList({ accountId: params.id || props.accountId }).then((res: any) => {
      res.result.forEach((item: any) => {
        item.status = 'create'
      })
      copyCustomCarList.value = JSON.stringify(res.result)
      form.value.customCarList.dataList = res.result
      shadowCustomCarList.list = form.value.customCarList.dataList.slice()
    })
  }

  onMounted(() => {
    loadData()
  })

  defineExpose({
    loadData,
    copyCustomCarList,
    shadowCustomCarList,
    queryParam,
  })
</script>

<style lang="less" scoped>
  .car-match-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .list-search-wrapper {
      width: 100%;
    }
    &__empty {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .arco-icon-empty {
        margin-bottom: 4px;
        color: rgba(216, 216, 216, 1);
      }

      span {
        font-size: 12px;
        font-weight: 400;
        margin-bottom: 8px;
        color: rgba(216, 216, 216, 1);
      }
    }

    &-count {
      width: 100%;
      display: flex;
      font-size: 14px;
      font-weight: 400;
      color: #4e5969;

      .item {
        display: flex;
        align-items: center;
        margin-right: 29px;

        &:last-child {
          margin-right: 0;
        }
      }
      .num {
        color: #1890ff;
      }
    }

    .btn-list {
      position: absolute;
      right: -190px;
      width: 190px;
      padding-left: 29px;
      .btn-item {
        font-size: 14px;
        height: 32px;
        line-height: 32px;
        white-space: nowrap;
        outline: none;
        cursor: pointer;
        user-select: none;
        padding: 0 5px;
        icon {
          margin-right: 8px;
        }
        &.del {
          color: #ea0000;
        }
        &.new {
          color: #165dff;
        }
      }
    }
  }
</style>
